package com.adkun.community.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Component //由Spring容器管理
public class MailClient {

    private static final Logger logger = LoggerFactory.getLogger(MailClient.class);

    @Autowired
    private JavaMailSender mailSender;

    // 自动将application.properties里面的邮箱用户名注入到from（发件人）中
    @Value("${spring.mail.username}")
    private String from;

    public void sendMail(String to, String subject, String content) {

        try {
            // 关键是把MimeMessage构建好，然后调用JavaMailSender的send()发送出去
            MimeMessage message = mailSender.createMimeMessage();

            // 用帮助类来给MimeMessage填入内容
            MimeMessageHelper helper = new MimeMessageHelper(message);
            helper.setFrom(from);  // 这个方法会抛出MessagingException
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true); //html字段true：默认普通文本，true则支持html文本

            // 发送邮件
            mailSender.send(helper.getMimeMessage());
        } catch (MessagingException e) {
            logger.error("发送邮件失败：" + e.getMessage());
        }
    }

    public String getFrom() {
        return from;
    }
}
